package com.wyl.home.search

import android.view.View
import androidx.databinding.ObservableArrayList
import androidx.recyclerview.widget.GridLayoutManager
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.extend.toDisposables
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.ObservableBody
import com.wuhenzhizao.titlebar.widget.CommonTitleBar
import com.wyl.base.HOME_SEARCH
import com.wyl.base.openVideoDetailPage
import com.wyl.home.R
import com.wyl.libbase.base.NormalActivity
import com.wyl.libbase.extend.autoWired
import io.ditclear.bindingadapter.ItemClickPresenter
import io.ditclear.bindingadapter.SingleTypeAdapter
import kotlinx.android.synthetic.main.search_list_activity.*

class SearchListActivity : NormalActivity(), ItemClickPresenter<Map<String, String>> {

    private val key by lazy { autoWired("key", "") }
    val dataSource = ObservableArrayList<Map<String, String>>()

    override fun getLayoutId(): Int = R.layout.search_list_activity

    override fun initView() {
        titlebar.setListener { _, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_LEFT_BUTTON -> onBackPressed()
                else -> {
                }
            }
        }

        recyclerView.apply {
            layoutManager = GridLayoutManager(context, 3)
            adapter = mAdapter
//            addItemDecoration(RecyclerViewDivider(context, RecyclerViewDivider.BOTH, dp2px(8f), Color.WHITE))
        }

        refreshLayout.apply {
            setEnableLoadmore(false)
            setOnRefreshListener(loadListener)
        }

    }

    private val mAdapter by lazy {
        SingleTypeAdapter(this, R.layout.home_item_video_list, dataSource)
            .apply {
                itemPresenter = this@SearchListActivity
            }
    }

    override fun onItemClick(v: View, item: Map<String, String>) {
        openVideoDetailPage(item["appFolkOperaId"])
    }

    override fun loadData() {
        refreshLayout.startRefresh()
        OkGo.post<BaseResponse<List<Map<String, String>>>>(HOME_SEARCH)
            .params("name", key)
            .converter(object : JsonConvert<BaseResponse<List<Map<String, String>>>>() {})
            .adapt(ObservableBody<BaseResponse<List<Map<String, String>>>>())
            .doFinally {
                refreshLayout.finishRefreshing()
                refreshLayout.setEnableRefresh(false)
            }
            .subscribe(
                {
                    dataSource.clear()
                    if (it.code == 1) {
                        empty.visibility = View.VISIBLE
                    } else {
                        dataSource.addAll(it.data)
                    }
                }, {
                    onError(it)
                    it.printStackTrace()
                }
            ).toDisposables(disposables)
    }

}
